package com.vogue.supplymall.order.controller;

import java.util.List;

import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.vogue.configs.springextend.remote.DelegateResource;
import com.vogue.sprakka.client.future.FutureWrapper;
import com.vogue.supplymall.common.constant.ConstantBean;
import com.vogue.supplymall.common.constant.ErrorCode;
import com.vogue.supplymall.common.domain.dto.ControllerResultInfo;
import com.vogue.supplymall.common.domain.dto.MultiplePayInfo;
import com.vogue.supplymall.common.domain.dto.OrderInfo;
import com.vogue.supplymall.common.domain.tool.MessageSourceUtils;
import com.vogue.supplymall.common.exception.DataNotFindException;
import com.vogue.supplymall.order.domain.biz.OrderPayBiz;
import com.vogue.supplymall.order.domain.biz.OrderUpdateBiz;
import com.vogue.supplymall.order.domain.service.OrderService;
import com.vogue.supplymall.order.domain.service.OrderBuyerService;
import com.vogue.supplymall.order.domain.service.OrderPaymentService;
import com.vogue.supplymall.order.domain.service.OrderStatusService;
import com.vogue.supplymall.order.exception.OrderIsTimeOverException;
import com.vogue.supplymall.payment.api.WuXiangPayment;
import com.vogue.supplymall.payment.dto.BaseResultParameter;
import com.vogue.supplymall.payment.dto.IResultParameter;
import com.vogue.supplymall.payment.dto.InputParameter;
import com.vogue.supplymall.payment.dto.ResultParameter;

/**
 * 订单支付接口
 * 
 * @author 崔岳
 *
 */
@RestController
public class OrderPayController extends BaseController {

	public static final Logger LOGGER = LoggerFactory.getLogger(OrderPayController.class);
	
	@Resource
	private OrderService orderService;

	@Resource
	private OrderBuyerService orderBuyerService;
	
	@Resource
    private OrderPayBiz orderPayBiz;
	
    @DelegateResource
    private WuXiangPayment wuXiangPayment;
    
    @Resource
    private OrderPaymentService orderPaymentService;
    
    @Resource
    private OrderUpdateBiz orderUpdateBiz;
    
	@Resource
	private OrderStatusService orderStatusService;
	
    @Autowired
    protected MessageSourceUtils messageSourceUtils;
	
    /**
     * 订单退款（指退款不做其他操作，可以理解成一种补救措施的方法）
     * @param appver 版本号
     * @param orderInfo 封装的订单信息
     * @return 退款结果
     */
	@RequestMapping(value = "/is/{appver}/order/paycancel", method = RequestMethod.POST)
	public ResponseEntity<Object> orderPayCancel(@PathVariable("appver") String appver,
			@RequestBody OrderInfo orderInfo) {
	    IResultParameter crp = null;
		try {
		    crp = orderPayBiz.orderRefund(orderInfo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			crp = new BaseResultParameter();
			crp.setReturnCode(-1);
			crp.setErrorText(e.getMessage());
			crp.setErrorCode("404");
			LOGGER.error("Paycancel is error:" + e.toString());
		}
		ControllerResultInfo resultInfo = new ControllerResultInfo();
		if (HttpStatus.OK.toString().equals(crp.getErrorCode())) {
			resultInfo.setData(crp.getData());
			resultInfo.setResult(true);
			resultInfo.setMsg(crp.getErrorText());
		} else {
			resultInfo.setResult(false);
			resultInfo.setMsg(crp.getErrorText());
			try {				
				resultInfo.setCode(Integer.parseInt(crp.getErrorCode()));
			}catch(NumberFormatException nfex) {
			    LOGGER.error("错误编码转换失败返回的是[{}]无法转换",crp.getErrorCode());
			}	
		}
		return new ResponseEntity<>(resultInfo, HttpStatus.OK);
	}
	
	/**
	 * 支付调用接口
	 * @param appver 版本号
	 * @param multiplePayInfo 订单信息封装
	 * @return 支付结果对象
	 */
	@RequestMapping(value = "/is/{appver}/order/pay/multiple", method = RequestMethod.POST)
    public ResponseEntity<Object> orderPayMultiple(@PathVariable("appver") String appver,
            @RequestBody MultiplePayInfo multiplePayInfo) {
	    LOGGER.debug("order pay multiple start >>>>>> ");
        ControllerResultInfo resultInfo = new ControllerResultInfo();
        IResultParameter iResultParameter = orderPayBiz.orderPay(multiplePayInfo);
        if (iResultParameter.getReturnCode() == -1) {
            if ("0".equals(iResultParameter.getErrorCode())) {
                throw new DataNotFindException(iResultParameter.getErrorText());
            } else {
                if (String.valueOf(ErrorCode.OrderIsTimeOver.getCode()).equals(iResultParameter.getErrorCode())) {
                    throw new OrderIsTimeOverException(iResultParameter.getErrorText());
                }
            }
        }
        resultInfo.setResult(true);
        resultInfo.setCode(ConstantBean.SHAREGO_SUCCESS_CODE);
        resultInfo.setMsg(messageSourceUtils.getMessage("order.pay.success", null));
        resultInfo.setData(iResultParameter);
        LOGGER.debug(" <<<<<< order pay multiple end");
        return new ResponseEntity<>(resultInfo, HttpStatus.OK);
	}
	
	@SuppressWarnings("rawtypes")
    @RequestMapping(value = "/ns/{appver}/order/ddbl", method = RequestMethod.POST)
    public ResponseEntity<Object> ddbl(@PathVariable("appver") String appver) {
//	    OrderInfo oi = new OrderInfo();
//	    try {
//	        orderUpdateBiz.payOnline(oi);
//	    } catch (Exception ex) {
//	        
//	    }
//	    try {
//	        orderPayBiz.orderPay(oi);
//        } catch (Exception ex) {
//            
//        }	    
	    InputParameter input = new InputParameter();
	    try {
            @SuppressWarnings("unchecked")
            FutureWrapper<ResultParameter> wrapper = FutureWrapper.wrapper( wuXiangPayment, gt -> {
                try {
                    gt.commPayGetUrl(input, null, null);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }, ResultParameter.class );
            logger.info( wrapper.get().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
	}
}
